package reflect;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @Classname: ReflectDemo7
 * @Author: bromide
 * @CreateTime: 2022/4/18--16:24
 * @Version: V1.0
 * @Description: 自动调用与当前类ReflectDemo7所在同一个包中，自动调用本类自己定义的公开的无参方法
 */
public class ReflectDemo7 {
    public static void main(String[] args) throws Exception {
        /*
            两个开发中常用的相对路径
         */
        //1
        File dir = new File(ReflectDemo7.class.getResource(".").toURI());
        String packageName = ReflectDemo7.class.getPackage().getName();
        File[] files = dir.listFiles(file -> file.getName().endsWith(".class"));
        for (File file : files) {
            String fileName = file.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            System.out.println("================" + className);
            Class cls = Class.forName(packageName + "." + className);
            Object obj = cls.newInstance();
            Method[] methods = cls.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getModifiers() == Modifier.PUBLIC && method.getParameterCount() == 0) {
                    method.invoke(obj);
                }
            }
        }
    }
}
